---- 同步报告器
local reporter = {}

local json = require "cjson"
local metadata_shdict = ngx.shared.tracing_buffer
local Const = require('skywalking.constants')

function reporter.new(_logger, backend_http_uri)
    if not backend_http_uri then
        return
    end
    return setmetatable({ logger = _logger , backend_http_uri = backend_http_uri}, { __index = reporter })
end

function reporter:boot(...)
end

local function sendSegments(segmentTransform, backend_http_uri)
    local log = ngx.log
    local ERR = ngx.ERR

    local http = require('resty.http')
    local httpc = http.new()

    local res, err = httpc:request_uri(backend_http_uri .. '/v3/segments', {
        method = "POST",
        body = segmentTransform,
        headers = {
            ["Content-Type"] = "application/json",
        },
    })

    if err == nil then
        if res.status ~= 200 then
            log(ERR, "Segment report fails, response code ", res.status)
            return false
        end
    else
        log(ERR, "Segment report fails, ", err)
        return false
    end

    return true
end

function reporter:send(reporter_spans)
    if not reporter_spans then
        self.logger.error("reporter_spans is null")
        return
    end
    local segmentJson, err = json.encode(reporter_spans)

    if not segmentJson then
        self.logger.error("failed to encode segment: " .. tostring(err))
        return
    end

    self.logger.info('http_reporter_segmentJson = '.. tostring(segmentJson))
    sendSegments('[' .. segmentJson .. ']', self.backend_http_uri)
    -- local length, err = metadata_shdict:lpush(Const.segment_queue, segmentJson)

    -- if not length then
    --     self.logger.error("failed to push segment: " .. tostring(err))
    --     return
    -- end
end

return reporter